package learn.Thread;

//顺序打印ABC
public class ThreadABC {
    public static void main(String[] args) {
        Thread a = new ThreadPrintABC("A",0);
        Thread b = new ThreadPrintABC("B",1);
        Thread c = new ThreadPrintABC("C",2);
        a.start();
        b.start();
        c.start();
    }
}


//顺序打印ABC的基本实现
class ThreadPrintABC extends Thread{
    //获取一个锁对象
    //这里注意！静态变量是属于方法的，非静态是属于对象的。在这个实例中，为了保证每个线程拿到的锁，以及计数器是共享的，需要把锁和计数器设置为静态。
    private static Object lock = new Object();
    private static int countNumber = 0;


    private int flag ;
    private String value;

    public ThreadPrintABC(String value,int flag){
        this.value = value;
        this.flag = flag;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            synchronized (lock) {
                while (countNumber % 3 != flag) {
                    try {
                        //这里使用wait释放锁，暂时阻塞让别的线程来执行
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(value);
                countNumber++;
                //通知其他线程来
                lock.notifyAll();
            }
        }
    }
}